package xmltomce.properties;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;


public class PersistentProperties{
	private static final String propertyFileName = "Settings.xml";
	private static PersistentProperties PROPERTIES;
	private Properties properties;
	private DefaultProperties defaultProperties;
	
	
	private PersistentProperties(DefaultProperties defaultProperties){
		if (defaultProperties != null){
			this.defaultProperties = defaultProperties;
		}
		properties = new Properties();
		load();
	}
	
	public static PersistentProperties getInstance(DefaultProperties defaultProperties){
		if (PROPERTIES == null){
			PROPERTIES = new PersistentProperties(defaultProperties);
		}
		return PROPERTIES;
	}
	
	public static PersistentProperties getInstance(){
		return PersistentProperties.getInstance(null);
	}
	
	private void load(){
		try {
			File xmlProperties = new File(getPropertiesFilePath());
			FileInputStream fis = new FileInputStream(xmlProperties);
			BufferedInputStream bis = new BufferedInputStream(fis);
			properties.loadFromXML(bis);
		} catch (Exception e) {
			setDefaultProperties();
		}
	}
	
	private void setDefaultProperties(){
		if (defaultProperties != null){
			properties.putAll(defaultProperties.getDefaultProperties());
		}
	}
	
	public void save(){
		try {
			FileOutputStream fos = new FileOutputStream(getPropertiesFilePath());
			BufferedOutputStream bos = new BufferedOutputStream(fos);
			properties.storeToXML(bos, null);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static String getPropertiesFilePath(){
		return PersistentProperties.getAppPath()+ "\\" + propertyFileName;
	}
	
	public static String getAppPath() {
		File runFolder = new File(PersistentProperties.class.getProtectionDomain().getCodeSource().getLocation().getPath());
		String appPath = runFolder.getParent().replaceAll("%20", " ");
		return appPath;
	}
	
	public void setProperty(String key, String value){
		properties.setProperty(key, value);
	}
	
	public String getProperty(String key){
		return properties.getProperty(key);
	}
	
}
